<template>
  <el-dialog
    :title="title"
    :visible.sync="openSheet"
    width="500px"
    :destroy-on-close="true"
    :close-on-click-modal="false"
  >
    <el-form ref="form" :model="form" label-width="120px">
      <el-form-item :label="$t('roleCode')">
        <el-input
          v-model="form.code"
          maxlength="32"
          disabled
          show-word-limit
          :placeholder="$t('inputRoleCode')"
        />
      </el-form-item>
      <el-form-item :label="$t('administrator')">
        <el-switch v-model="form.is_admin" disabled />
      </el-form-item>
      <el-form-item :label="$t('roleAuthorize')">
        <el-tree
          ref="tree"
          class="tree-border"
          :props="defaultProps"
          highlight-current
          :data="menuList"
          show-checkbox
          node-key="id"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">{{
        $t('update')
      }}</el-button>
      <el-button @click="cancel">{{ $t('cancel') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getRoleMenuApi,
  updateRoleMenuApi
} from '@/views/rbac/api/rbac.api';
export default {
  data() {
    return {
      title: this.$t('roleAuthorize'),
      openSheet: false,
      menuList: [],
      checkedList: [],
      menuQueryParams: {
        role: undefined,
        parent: undefined
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      form: {
        id: undefined,
        code: undefined,
        is_admin: false
      }
    };
  },
  methods: {
    async openSheetDialog(data) {
      this.openSheet = !this.openSheet;
      this.form = data;
      this.menuQueryParams.role = this.form.id;
      var resp = await getRoleMenuApi(this.menuQueryParams);
      if (resp.success) {
        this.menuList = resp.data.menu;
        this.$nextTick(() => {
          if (this.checkedList) {
            this.$refs.tree.setCheckedKeys(resp.data.checked);
          }
        });
      } else {
        this.targaMessageBox(this, resp.msg)
      }
    },
    cancel() {
      this.openSheet = !this.openSheet;
    },
    reset() {
      this.form = {
        code: undefined,
        is_admin: false
      };
      this.resetForm('form');
    },
    async submitForm() {
      var res = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
      var data = { 'role': this.form.id, 'selected': res }
      var resp = await updateRoleMenuApi(data)
      if (resp.success) {
        this.targaMessage(
          this.$t('updateSuccess', {
            title: this.$t('role'),
            value: this.form.code
          })
        );
      } else {
        this.targaMessageBox(this.title, resp.msg);
      }
    }
  }
};
</script>

<style></style>
